/**
 * JAVACC DEMO 1.0
 */
package com.apache.websocket;

import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * description:  客户端实现
 *
 * @author dyhou 创建时间：2017-6-20
 */
public class WebsocketClient {

    private Logger log = Logger.getLogger("web socket");

    private static Map<String,WebsocketEndpoint> clients = new HashMap<String,WebsocketEndpoint>();

    private WebsocketClient() {
    }

    private static class WebsocketClientHeader{
        public static final WebsocketClient client = new WebsocketClient();
    }

    public static WebsocketClient getInstance() {
         return WebsocketClientHeader.client;
    }

    public void sendMessage(final String configKey, final String url, final String requestParams,
            final String message) {
        String urlPath = StrUtil.doNull(ToolsUtil.getInstance().getValueByKey(configKey), url);
        String cacheKey=urlPath + StrUtil.doNull(requestParams, "");
        log.info("[websocket push message]->"+message);
        synchronized (this) {
            WebsocketEndpoint clientEndPoint = clients.get(cacheKey);
            try {
                if (null == clientEndPoint) {
                    clientEndPoint = WebsocketEndpoint.getWebsocketClient(cacheKey);
                    do {
                        this.wait(300);
                    } while (!clientEndPoint.isOpen());
                    clients.put(cacheKey, clientEndPoint);
                }
                // send message to websocket
                clientEndPoint.send(message);
                // wait 5 seconds for messages from websocket
            } catch (Exception ex) {
                log.error("web socket exception: " + ex.getMessage());
            }
        }

//        new Thread(new Runnable() {
//
//            public void run() {
//                WebsocketEndpoint clientEndPoint = null;
//                try {
//                    clientEndPoint = WebsocketEndpoint
//                            .getWebsocketClient(configKey, url, requestParams);
//                    do {
//                        Thread.sleep(300);
//                    } while (!clientEndPoint.isOpen());
//
//                    // send message to websocket
//                    clientEndPoint.send(message);
//                    // wait 5 seconds for messages from websocket
//                    Thread.sleep(3000);
//                } catch (Exception ex) {
//                    log.error("web socket exception: " + ex.getMessage());
//                } finally {
//                    if (null != clientEndPoint) {
//                        clientEndPoint.close();
//                    }
//                    clientEndPoint = null;
//                }
//            }
//        }).start();
    }

    public void sendMessageJson(final String websocketUrl, final String websocketType,final String sysPass, final String message) {
        String cacheKey=websocketUrl + websocketType+ StrUtil.doNull(sysPass, "");
        log.info("[websocket push url]->"+cacheKey);
        log.info("[websocket push type]->"+websocketType);
        log.info("[websocket push message]->"+message);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type",websocketType);
        jsonObject.put("message",message);
        String messageAll = jsonObject.toString();
        synchronized (this) {
            WebsocketEndpoint clientEndPoint = clients.get(cacheKey);
            try {
                if (null == clientEndPoint) {
                    clientEndPoint = WebsocketEndpoint.getWebsocketClient(cacheKey);
                    do {
                        this.wait(300);
                    } while (!clientEndPoint.isOpen());
                    clients.put(cacheKey, clientEndPoint);
                }
                // send message to websocket
                clientEndPoint.send(messageAll);
                // wait 5 seconds for messages from websocket
            } catch (Exception ex) {
                log.error("[websocket push exception]->"+ex.getMessage());
                log.error(ex);
            }
        }
    }


    public void sendMessage(String url, Map<String, String> httpHeaders, String message) {
        synchronized (this) {
            WebsocketEndpoint clientEndPoint = clients.get(url);
            try {
                if (null == clientEndPoint) {
                    clientEndPoint = WebsocketEndpoint.getWebsocketClient(url,httpHeaders);
                    do {
                        this.wait(300);
                    } while (!clientEndPoint.isOpen());
                    clients.put(url, clientEndPoint);
                }
                // send message to websocket
                clientEndPoint.send(message);
            } catch (Exception ex) {
                log.error("web socket exception: " + ex.getMessage());
            }
        }
    }

    public static void main(String args[]) {
        String sysPass = "?sysPass=e0cea4bb45e36c115356e46910c354af";
        WebsocketClient.getInstance()
                .sendMessage("", "ws://localhost:11003/flowSocket", sysPass, "processInsId");
    }
}
